package com.xiaoqi.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.xiaoqi.constant.MessageConstant;
import com.xiaoqi.pojo.OrderSetting;
import com.xiaoqi.pojo.Result;
import com.xiaoqi.service.OrderSettingService;
import com.xiaoqi.utils.POIUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;


import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author PC
 * creationTime: 2022/11/10 14:42
 */

@RequestMapping("/ordersetting")
@RestController
public class OrderSettingController {

    @Reference
    OrderSettingService orderSettingService;

    /**
     * 上传表格
     * @param excelFile
     * @return
     */
    @PostMapping("/upload")
    public Result upload(@RequestParam("excelFile") MultipartFile excelFile) {
        try {
            //获取表格中的数据
            List<String[]> Excel = POIUtils.readExcel(excelFile);
            //格式化时间
            SimpleDateFormat sdf = new SimpleDateFormat(POIUtils.DATE_FORMAT);

            List<OrderSetting> os = new ArrayList<>();
            //将数据转成对象,方便存入数据库里
            for (String[] row : Excel) {
//            将字符串转成时间,日期
                Date date = sdf.parse(row[0]);
//            将字符串转成数字,可预约人数
                int number = Integer.parseInt(row[1]);
//            创建预约设置的对象将数据放如对象
                OrderSetting orderSetting = new OrderSetting(date, number);
                os.add(orderSetting);
            }
            //将数据传入service
            orderSettingService.add(os);
            return new Result(true, MessageConstant.IMPORT_ORDERSETTING_FAIL);
        }catch (Exception e){
            e.printStackTrace();
            //9.失败
            return new Result(false, MessageConstant.IMPORT_ORDERSETTING_FAIL);
        }
    }

    /**
     * 通过月份查询这个月的预约情况
     * @param date
     * @return
     */
    @GetMapping("/getDataByMonth")
    public Result getDataByMonth(@RequestParam(value = "date")String date){
        List<Map<String, Object>> list = orderSettingService.findByMonth(date);
        return new Result(true,MessageConstant.GET_ORDERSETTING_SUCCESS,list);
    }


    /**
     * 对传入的日期进行可预约人数的编辑
     * @param orderSetting
     */
    @PostMapping("/editNumberByDate")
    public Result editNumberByDate(@RequestBody OrderSetting orderSetting){
        orderSettingService.editNumberByDate(orderSetting);
        return new Result(true, MessageConstant.GET_ORDERSETTING_SUCCESS);
    }
}
